- Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy path637. Average of Levels in Binary Tree.go
47 lines (43 loc) · 933 Bytes
/
637. Average of Levels in Binary Tree.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
typeTreeNode= structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
funcaverageOfLevels(root*TreeNode) []float64 {
ifroot==nil {
return []float64{0}
}
queue:= []*TreeNode{}
queue=append(queue, root)
curNum, nextLevelNum, res, count, sum:=1, 0, []float64{}, 1, 0
forlen(queue) !=0 {
ifcurNum>0 {
node:=queue[0]
ifnode.Left!=nil {
queue=append(queue, node.Left)
nextLevelNum++
}
ifnode.Right!=nil {
queue=append(queue, node.Right)
nextLevelNum++
}
curNum--
sum+=node.Val
queue=queue[1:]
}
ifcurNum==0 {
res=append(res, float64(sum)/float64(count))
curNum, count, nextLevelNum, sum=nextLevelNum, nextLevelNum, 0, 0
}
}
returnres
}